package com.eneat.smartrule.service;

import com.eneat.smartrule.model.RuleAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Map;

@Service
public class ActionExecutor {

    @Autowired
    private ApplicationContext context;

    public void execute(RuleAction action, Map<String, Object> env) {
        try {
            switch (action.getActionType()) {
                case METHOD_CALL:
                    executeMethodCall(action, env);
                    break;
                case HTTP_REQUEST:
                   // executeHttpRequest(action, env);
                    break;
                default:
                    throw new IllegalArgumentException("不支持的动作类型: " + action.getActionType());
            }
        } catch (Exception e) {
            System.err.println("动作执行失败：" + e.getMessage());
        }
    }

    /**
     * 执行方法调用
     */
    private void executeMethodCall(RuleAction action, Map<String, Object> env) throws Exception {
        Object targetBean = getTargetBean(action);

        Method method = resolveMethod(targetBean.getClass(), action.getMethodName(), action.getParameters());

        Object[] args = new Object[method.getParameterCount()];
        for (int i = 0; i < method.getParameterCount(); i++) {
            String paramName = method.getParameters()[i].getName();
            args[i] = action.getParameters().get(paramName);
        }

        method.invoke(targetBean, args);
    }

    /**
     * 从spring容器中获取bean，根据bean的名称
     */
    private Object getTargetBean(RuleAction action) {
        if (action.getTargetBeanName() != null) {
            return context.getBean(action.getTargetBeanName());
        }
        throw new IllegalArgumentException("未指定目标 Bean 或类");
    }

    // 根据参数名称和类型自动匹配方法
    private Method resolveMethod(Class<?> clazz, String methodName, Map<String, Object> parameters) throws NoSuchMethodException {
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                if (method.getParameterCount() == parameters.size()) {
                    return method;
                }
            }
        }
        throw new NoSuchMethodException("找不到匹配的方法: " + methodName);
    }
}
